package me.leon.keeplive

import android.app.*
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.IBinder
import android.os.SystemClock
import android.util.Log
import androidx.core.app.NotificationCompat

class ExactWorkService : Service() {

    private val alarmMgr by lazy { getSystemService(Context.ALARM_SERVICE) as AlarmManager }
    private val notificationMgr by lazy {
        getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    }

    override fun onCreate() {
        super.onCreate()
        Log.d("heartbeat", "onCreate $this")
        if (Build.VERSION.SDK_INT >= 26) {
            if (!isHideNotification) {
                val channel =
                    NotificationChannel(
                        channelId,
                        "为确保功能正常使用,请勿删除",
                        NotificationManager.IMPORTANCE_DEFAULT
                    )
                notificationMgr.createNotificationChannel(channel)
            }

            val notification =
                NotificationCompat.Builder(this, channelId)
                    .setContentTitle("")
                    .setPriority(NotificationCompat.PRIORITY_MIN)
                    .setContentText("")
                    .build()
            Log.d("heartbeat", "startForeground")
            startForeground(1, notification)
            // 停止后,通知栏不显示通知,但是每次都会创建新服务,而不是走 onStartCommand
            if (isHideNotification) {
                stopSelf()
            }
        }
    }

    override fun onBind(intent: Intent?): IBinder? = null

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d("heartbeat", "AlarmService")

        // 事件交互, 注册广播进行事件监听
        sendBroadcast(
            Intent(ACTION).apply {
                this.flags = Intent.FLAG_INCLUDE_STOPPED_PACKAGES
                putExtra("package", packageName)
            }
        )

        // 退到后台后 定时器无法准确定时执行, 需要用系统 ALARM_SERVICE 保证定时执行
        val triggerAtTime: Long = SystemClock.elapsedRealtime() + intervalSeconds * 1000L
        val i =
            Intent(this, HeartBeatReceiver::class.java).apply {
                addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
            }
        val pi = PendingIntent.getBroadcast(this, 0, i, 0)
//        alarmMgr.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi)
        alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME,0,triggerAtTime,pi)
        return START_STICKY
    }

    class MsgReceiver(private val block: (msg: Intent?) -> Unit) : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent?.getStringExtra("package") == context?.packageName) block.invoke(intent)
        }
    }

    companion object {
        private const val ACTION = "me.leon.message"
        private const val channelId = "channel_keep_live"
        private var intervalSeconds = 60
        private var isHideNotification = false

        fun cancelAlarm(ctx: Context) {
            val manager = ctx.getSystemService(Context.ALARM_SERVICE) as AlarmManager
            val i = Intent(ctx, HeartBeatReceiver::class.java)
            val pi = PendingIntent.getBroadcast(ctx, 0, i, 0)
            manager.cancel(pi)
        }

        /** interval >5, 太小不准确 */
        fun launch(ctx: Context, interval: Int, hideNotification: Boolean = false) {
            intervalSeconds = interval
            isHideNotification = hideNotification
            ctx.startService(Intent(ctx, ExactWorkService::class.java))
        }

        /** 需要手动 注销 receiver block 进行定时任务 */
        fun addCallback(ctx: Context, work: (msg: Intent?) -> Unit): MsgReceiver {
            val receiver = MsgReceiver(work)
            ctx.registerReceiver(receiver, IntentFilter().apply { addAction(ACTION) })
            return receiver
        }
    }
}
